import React, { Component } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import './editQuestion.less';
import E from 'wangeditor';
import { Input, Button } from 'antd';
import { Questions_List_Item, Update_Question } from '@/type/watchQuestion';
import { WatchQuestionModelState } from '@/models/watchQuestion';
import { connect } from 'umi';

interface Match {
  id: string;
}

interface IStateModel {
  watchQuestion: WatchQuestionModelState;
}

interface IProps extends RouteComponentProps<Match> {
  questionList: Questions_List_Item[];
  getQuestionsList: () => void;
  getDetailQuestions: (payload: string) => void;
  updateQuestion: (payload: Update_Question) => void;
  detail: any;
}
class EditQuestion extends Component<IProps> {
  //富文本编辑器
  editor: any = null;

  state = {
    title: '', //标题
  };
  //初始化富文本编辑器,获取详情信息
  componentDidMount() {
    this.editor = new E('.questions_stem');
    this.editor.create();
    this.props.getDetailQuestions(this.props.match.params.id);
  }
  //初始复值，数据回显
  UNSAFE_componentWillReceiveProps(nextProp: IProps) {
    this.editor.txt.html(nextProp.detail.questions_stem);
    this.setState({ title: nextProp.detail.title });
  }
  //提交，修改question
  changeQuestion() {
    let { title } = this.state;
    this.props.updateQuestion({
      questions_id: this.props.match.params.id,
      title,
      questions_stem: this.editor.txt.text(),
    });
  }
  //改变值
  changeValue(e: any) {
    this.setState({
      title: e.target.value,
    });
  }

  render() {
    let { title } = this.state;
    return (
      <div className="editQuestion">
        <p>编辑试题</p>
        <div className="editQuestion_con">
          <p>题目信息</p>
          <div className="">
            <p>题干</p>
            <Input
              style={{ width: '40%' }}
              value={title}
              onChange={this.changeValue.bind(this)}
            />
          </div>
          <div className="">
            <p>题目主题</p>
            <div className="questions_stem"></div>
          </div>
          <Button
            type="primary"
            style={{ marginTop: '20px' }}
            onClick={this.changeQuestion.bind(this)}
          >
            提交
          </Button>
        </div>
      </div>
    );
  }
}
export default connect(
  (state: IStateModel) => {
    return { ...state.watchQuestion };
  },
  (dispatch) => {
    return {
      getQuestionsList() {
        dispatch({ type: 'watchQuestion/GET_QUESTION_LIST' });
      },
      getDetailQuestions(payload: string) {
        dispatch({ type: 'watchQuestion/GET_DETAIL_QUESTION', payload });
      },
      updateQuestion(payload: Update_Question) {
        dispatch({ type: 'watchQuestion/UPDATE_QUESTION', payload });
      },
    };
  },
)(EditQuestion);
